﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using ClimateControl.Infrastructure.Service.Server;
using System.Threading;
using System.ServiceModel.Description;
using ClimateControl.Infrastructure.Service;

namespace ClimateControl.Service
{
    public partial class ClimateWindowsService : ServiceBase
    {
        IClimateService climateService;
        ServiceHost serviceHost;

        public ClimateWindowsService()
        {
            this.ServiceName = ServiceHelper.GetWindowsServiceName();
            this.CanStop = true;
            this.CanPauseAndContinue = true;
            this.AutoLog = true;
        }

        protected override void OnStart(string[] args)
        {
            climateService = new ClimateService();

            serviceHost = new ServiceHost(climateService);
            serviceHost.AddServiceEndpoint(typeof(IClimateService), ServiceHelper.GetBinding(), ServiceHelper.GetUri("localhost"));

            serviceHost.Open();
        }

        protected override void OnStop()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }

        /// <summary>
        /// Main method to control if running as app or service
        /// </summary>
        public static void Main()
        {
#if DEBUG
                //// Run as interactive exe in debug mode to allow easy
                //// debugging.

                var service = new ClimateWindowsService();
                service.OnStart(null);

                //// Sleep the main thread indefinitely while the service code
                //// runs in .OnStart

                Thread.Sleep(Timeout.Infinite);
                //service.Dispose();
                //service = null; 
#else
            System.ServiceProcess.ServiceBase.Run(new ClimateWindowsService());
#endif
        }
    }
}
